<!--********************************************************************
* Copyright© 2000 - 2018 SuperMap Software Co.Ltd. All rights reserved.
*********************************************************************-->
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title data-i18n="resources.title_dynamicPieChart"></title>
    <style type="text/css">
        .arc path {
            stroke: #fff;
        }
    </style>
</head>
<body style=" margin: 0;overflow: hidden;background: #fff;width: 100%;height:100%;position: absolute;top: 0;">
<div id="map" style="margin:0 auto;width: 100%;height: 100%"></div>
<script type="text/javascript" include="bootstrap,widgets.alert" src="../js/include-web.js"></script>
<script type="text/javascript" exclude="iclient-classic" include="d3"
        src="../../dist/classic/include-classic.js"></script>
<script type="text/javascript">
    var map, layer, utfgrid, control, d3Layer,
        host = window.isLocal ? window.server : "http://support.supermap.com.cn:8090",
        url = host + "/iserver/services/map-china400/rest/maps/China";
    var pieChartDom;
    var elementsDiv;
    var isMapMoving = false;

    //判断浏览器是否支持 Svg
    function hasSVG() {
        var doc = document;
        var SVG_NS = 'http://www.w3.org/2000/svg';
        return !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect;
    }

    function init() {
        if (!hasSVG()) {
            widgets.alert.showAlert(resources.msg_supportSVG, false);
            return;
        }

        //ie 9 支持 svg，但不完善，不能正常运行此范例
        if (SuperMap.Browser.name === "msie" && SuperMap.Browser.version.indexOf("9") !== -1) {
            widgets.alert.showAlert(resources.msg_supportInstance, false);
            return;
        }

        map = new SuperMap.Map("map", {
            controls: [
                new SuperMap.Control.ScaleLine(),
                new SuperMap.Control.Zoom(),
                new SuperMap.Control.LayerSwitcher(),
                new SuperMap.Control.Navigation({
                    dragPanOptions: {
                        enableKinetic: true
                    }
                })],
            projection: "EPSG:3857"
        });

        //地图移动过程中不显示图表
        map.events.on({
            "movestart": function () {
                document.getElementById("piechart").innerHTML = "";
                isMapMoving = true;
            }
        });
        map.events.on({
            "moveend": function () {
                isMapMoving = false;
            }
        });

        //基础图层
        layer = new SuperMap.Layer.TiledDynamicRESTLayer("China", url, {transparent: true}, {
            useCanvas: true,
            maxResolution: "auto"
        });

        //创建 Elements 图层，用于显示饼图
        d3Layer = new SuperMap.Layer.Elements("D3Layer");

        //获取 Elements 图层 div
        elementsDiv = d3Layer.getDiv();
        //设置Elements实例的div为地图大小
        var mapsize = map.getSize();
        elementsDiv.style.width = mapsize.w;
        elementsDiv.style.height = mapsize.h;

        //创建图表 div, 设置其基本属性, 并添加到  Elements 图层
        pieChartDom = document.createElement("div");
        pieChartDom.id = "piechart";
        pieChartDom.style.width = "128px";
        pieChartDom.style.height = "128px";
        pieChartDom.style.position = "absolute";
        pieChartDom.style.opacity = "0.8";
        elementsDiv.appendChild(pieChartDom);
        console.log(pieChartDom.style.width);

        //创建 UTFGrid 图层，用于更新饼图数据
        utfgrid = new SuperMap.Layer.UTFGrid("UTFGridLayer", url,
            {
                layerName: "China_Province_pl@China",
                utfTileSize: 256,
                pixcell: 8,
                isUseCache: true
            },
            {
                utfgridResolution: 8
            });

        layer.events.on({"layerInitialized": addLayer});
        control = new SuperMap.Control.UTFGrid({
            layers: [utfgrid],
            callback: callback,
            handlerMode: "move"
        });
        map.addControl(control);
    }

    $(document).ready(function () {
        init();
    });

    var callback = function (infoLookup, loc, pixel) {
        if (infoLookup && isMapMoving === false) {
            var info;
            for (var idx in infoLookup) {
                info = infoLookup[idx];
                if (info && info.data) {
                    document.getElementById("piechart").innerHTML = "";

                    //全国面积取 9.6e12（960万平方千米）
                    var anotherArea = 9.6e12 - info.data.SmArea;

                    // 计算面积比
                    var theArea = ((info.data.SmArea / 9.6e12) * 100).toFixed(2);
                    var allArea = ((anotherArea / 9.6e12) * 100).toFixed(2);

                    //组织 D3 PieDChart 数据
                    var data = [
                        {
                            "NAME": resources.text_otherProvince + allArea + "%",
                            "SmArea": anotherArea
                        },
                        {
                            "NAME": info.data.NAME + theArea + "%",
                            "SmArea": info.data.SmArea
                        }
                    ];

                    //取图表 div 大小作为创建图表的参数
//                    console.log(pieChartDom);
                    var width = parseFloat(128),
                        height = parseFloat(128),
                        radius = Math.min(width, height) / 2;

                    //图表位置
                    pieChartDom.style.left = pixel.x - width / 2+"px";
                    pieChartDom.style.top = pixel.y - height / 2+"px";

                    var color = d3.scale.ordinal()
                        .range(["#1874CD", "#87CEFA"]);

                    var arc = d3.svg.arc()
                        .outerRadius(radius - 10)
                        .innerRadius(0);

                    var pie = d3.layout.pie()
                        .sort(null)
                        .value(function (d) {
                            return d.SmArea;
                        });

                    var svg = d3.select("#piechart").append("svg")
                        .attr("width", width)
                        .attr("height", height)
                        .append("g")
                        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

                    //D3 饼图绘制
                    var g = svg.selectAll(".arc")
                        .data(pie(data))
                        .enter().append("g")
                        .attr("class", "arc");
                    g.append("path")
                        .attr("d", arc)
                        .style("fill", function (d) {
                            return color(d.data.NAME);
                        });
                    g.append("text")
                        .attr("transform", function (d) {
                            return "translate(" + arc.centroid(d) + ")";
                        })
                        .attr("dy", "0.35em")
                        .style("text-anchor", "middle")
                        .text(function (d) {
                            return d.data.NAME;
                        });
                }
                else {
                    //清除饼图
                    document.getElementById("piechart").innerHTML = "";
                }
            }
        }
    };

    //添加图层
    function addLayer() {
        var center = new SuperMap.LonLat(9733502.481499, 4614406.969325);
        map.addLayers([layer, d3Layer, utfgrid]);
        map.setCenter(center, 4);
    }
</script>
</body>
</html>